package com.magnificent.atlantis.client.data.alert;

import com.magnificent.atlantis.client.event.EventDispatcher;
import com.magnificent.atlantis.client.event.EventType;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * User: Babanin
 * Date: 13.02.2009
 * Time: 17:19:59
 */
@XmlRootElement(name = "alerts")
public class AlertsContainer {
    private List<AbstractAlert> abstractAlerts;

    public AlertsContainer() {
        abstractAlerts = new ArrayList<AbstractAlert>();
    }

    @XmlElement()
    public List<AbstractAlert> getAlerts() {
        long currentTime = new Date().getTime();
        Iterator<AbstractAlert> it = abstractAlerts.listIterator();
        while (it.hasNext()) {
            AbstractAlert abstractAlert = it.next();
            if (abstractAlert.getDate().getTime() - currentTime < 0){
                it.remove();
            }
        }

        return abstractAlerts;
    }

    public void newAlert(AbstractAlert alert) {
        abstractAlerts.add(alert);
        EventDispatcher.getInstance().postEvent(EventType.NEW_ALERT, alert);
    }

    public void removeAlert(AbstractAlert alert) {
        if (abstractAlerts.remove(alert)) {
            EventDispatcher.getInstance().postEvent(EventType.DELETE_ALERT, alert);
        }
    }

    public void setEvents(List<AbstractAlert> abstractAlerts) {
        this.abstractAlerts = abstractAlerts;
    }

    public int getImportantEventCount() {
        int result = 0;

        for (AbstractAlert abstractAlert : abstractAlerts) {
            if (abstractAlert.isImportant()) {
                result++;
            }
        }

        return result;
    }
}
